/**
 * 
 */
package info.niwota.profile;

import info.niwota.commons.web.ContentHelper;
import info.niwota.profile.web.Helper;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;

import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author qiangli
 * 
 */
public class PeerListAdapter extends BaseAdapter {
	// private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	private static final String DATE_FORMAT = "yy-MM-dd HH:mm";

	private static final String TAG = "PeerListAdapter";

	private SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);

	static class ViewHolder {
		private TextView date;
		private TextView desc;
		private ImageView icon;
		private TextView title;
	}

	private File[] profiles = null;

	private LayoutInflater inflater;

	private Context ctx;

	private Bitmap AVATAR_DEF;

	private int sort;

	private SharedPreferences pref;

	private Bitmap ICON_STAR;

	private Bitmap AVATAR_STAR;

	public PeerListAdapter(Context ctx, int sort) {
		this.ctx = ctx;
		//
		this.inflater = LayoutInflater.from(ctx);
		this.sort = sort;
		
		initImages();
	}

	public void load() {
		this.profiles = Helper.listVisited(ctx);
		this.pref = Preferences.getFavoritePeers(ctx);
		
		sortProfiles();
	}

	private void initImages() {
		try {
			AVATAR_DEF = BitmapFactory.decodeResource(ctx.getResources(),
					R.drawable.avatar_android48);
			AVATAR_STAR = BitmapFactory.decodeResource(ctx.getResources(),
					R.drawable.avatar_android_star48);
			ICON_STAR = BitmapFactory.decodeResource(ctx.getResources(),
					R.drawable.favorite10);
		} catch (Exception e) {
			//
		}
	}

	private void sortProfiles() {
		int cnt = getCount();
		if (cnt == 0) {
			return;
		}
		
		sortProfiles(ctx, profiles, sort);
	}

	public int getCount() {
		return (profiles == null ? 0 : profiles.length);
	}

	public JSONObject getItem(int pos) {
		try {
			return ContentHelper.readObject(profiles[pos]);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JSONObject();
	}

	public long getItemId(int pos) {
		return pos;
	}

	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder holder;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.list_item, null);
			holder = new ViewHolder();
			holder.title = (TextView) convertView
					.findViewById(R.id.list_item_title);
			holder.date = (TextView) convertView
					.findViewById(R.id.list_item_desc2);
			holder.desc = (TextView) convertView
					.findViewById(R.id.list_item_desc);
			holder.icon = (ImageView) convertView
					.findViewById(R.id.list_item_icon);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		JSONObject item = getItem(position);
		if (Debug.DEBUG) {
			Log.d(TAG, "getView: " + item);
		}
		String peer = getString(item, "peer");
		holder.title.setText(peer);
		File file = profiles[position];
		holder.date.setText(formatDate(file.lastModified()));
		holder.desc.setText(getString(item, "profile.name"));

		boolean star = Preferences.isPeerStarred(pref, peer);
		Bitmap thumb = getThumb(peer, star);
		holder.icon.setImageBitmap(thumb);

		return convertView;
	}

	private Bitmap getThumb(String peer, boolean star) {
		if (Debug.DEBUG) {
			Log.d(TAG, "peer: " + peer + " star: " + star);
		}
		try {
			Bitmap bm = Helper.loadCachedPeerThumb(ctx, peer);
			if (bm != null) {
				if (star) {
					bm = Utils.decorate(bm, 48, 48, ICON_STAR);
				} else {
					bm = Utils.thumb(bm, 48, 48);
				}
				return bm;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return star ? AVATAR_STAR : AVATAR_DEF;
	}

	private CharSequence formatDate(long lastTime) {
		if (lastTime <= 0) {
			return "";
		}
		return formatter.format(new Date(lastTime));
	}

	private String getString(JSONObject item, String key) {
		try {
			return item.getString(key);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return null;
	}

	public static final int SORT_FAV = 0;
	public static final int SORT_RECENT = 1;

	public static void sortProfiles(final Context ctx, File[] profiles, int sort) {
		final SharedPreferences pref = Preferences.getFavoritePeers(ctx);

		Comparator<? super File> comparator = null;

		if (sort == SORT_RECENT) {
			comparator = new Comparator<File>() {
				public int compare(File f1, File f2) {
					return (int) (f2.lastModified() - f1.lastModified());
				}
			};
		} else if (sort == SORT_FAV) {
			comparator = new Comparator<File>() {
				public int compare(File f1, File f2) {
					String n1 = f1.getName();
					String n2 = f2.getName();
					boolean s1 = (Preferences.isPeerStarred(pref, n1));
					boolean s2 = (Preferences.isPeerStarred(pref, n2));

					if (s1 && !s2) {
						return -1;
					}
					if (!s1 && s2) {
						return 1;
					}

					return n1.compareTo(n2);
				}
			};
		}

		Arrays.sort(profiles, comparator);
	}
}
